<?php

namespace App\Service\delivery;
use App\Model\Applet;
use App\Model\AppletPlayletRel;
use App\Model\DataSpread;
use App\Model\DataUserPayPlayletLog;
use App\Model\DataUserRechargeLog;
use App\Model\Payment;
use App\Model\Playlet;
use App\Model\Company;
use App\Model\AppletCompany;
use App\Model\PlayletEpisodes;
use App\Model\RechargeGoods;
use App\Model\RechargeTemplate;
use App\Model\SystemOrderDay;
use App\Model\SystemUserDay;
use App\Service\CommicService;
use Hyperf\Utils\ApplicationContext;
use App\Common\Response\SystemCode;
use Hyperf\DbConnection\Db;

class StatisticsService extends CommicService
{
    const cacheDuration = 60 * 15;
    public function __construct()
    {
        $container = ApplicationContext::getContainer();
        $this->redisService = $container->get(\Hyperf\Redis\Redis::class);
        $this->userAppletIds = $this->getUserAppletInfo();
    }


    const STATUS_ENABLE  = 1;

    public function spreadSearch(Array $params,$export=0){

        $pageSize       = $params['pageSize'] ?? 10;
        $page           = $params['page'] ?? 1;
        $applet_ids     = $params['applet_ids'] ?? '';
        $data_spread_id = $params['data_spread_id'] ?? '';
        $spread_name    = $params['keyword'] ?? '';
        $playlet_id     = $params['playlet_id'] ?? '';
        $date     = $params['date'] ?? '';
        $delivery_user_id  = $params['delivery_user_id'] ?? '';
        if(empty($applet_ids)){
            return [];
        }
        $subSelect = '';
        //2023-12-11 新增可看到投放组员的数据
        if(!empty($delivery_user_id)){
//            $spreadIds = DataSpread::query()->whereIn('user_id',$delivery_user_id)->pluck('id');
            $delivery_str = implode(',',$delivery_user_id);
            $subSelect = "select `id` from `data_spread` where `user_id` in (".$delivery_str.") and `data_spread`.`deleted_at` is null";
        }else{
            $userInfo = $this->getUserAppletInfo(2);
            //管理员能看到所有
            if($userInfo['role']['is_admin'] != 1){
//                $spreadIds = DataSpread::query()->where(['user_id' => $userInfo['id']])->pluck('id');
                $subSelect = "select `id` from `data_spread` where `user_id` = ".$userInfo['id']." and `data_spread`.`deleted_at` is null";
            }
        }

        if($applet_ids == '1'){
            //获取所有的小程序所绑定的短剧
            $applet_id =  $this->userAppletIds;
        }else{
            $applet_id =  [$applet_ids];
        }
        $selectArr = ['date','data_spread_id','data_spread.name as spread_name'];
        $groupBy = ['date','data_spread_id'];
        if($playlet_id != '' && $playlet_id != 1){
            $selectArr[] ='system_order_day.playlet_id';
            $selectArr[] ='playlet.name as playlet_name';
            $groupBy[] = 'system_order_day.playlet_id';
        }

        $countArr = [
            Db::raw('SUM(order_count) as order_count'),
//            Db::raw('SUM(order_wait_pay_count) as order_wait_pay_count'),
            Db::raw('SUM(order_count) as order_pay_count'),
//            Db::raw('SUM(order_cannel_count) as order_cannel_count'),
//            Db::raw('SUM(order_return_count) as order_return_count'),
            Db::raw('SUM(order_wx_pay_count) as order_wx_pay_count'),
            Db::raw('SUM(order_virtually_pay_count) as order_virtually_pay_count'),
            Db::raw('SUM(first_user_count) as first_user_count'),
            Db::raw('SUM(first_user_pay_amonut) as first_user_pay_amonut'),
            Db::raw('SUM(today_first_user_pay_amonut) as today_first_user_pay_amonut'),
            Db::raw('SUM(today_first_user_pay_count) as today_first_user_pay_count'),
            Db::raw('SUM(today_after_user_pay_amonut) as today_after_user_pay_amonut'),
            Db::raw('SUM(today_after_user_pay_count) as today_after_user_pay_count'),
            Db::raw('SUM(order_amount) as order_amount'),
            Db::raw('SUM(order_wx_pay_amonut) as order_wx_pay_amonut'),
            Db::raw('SUM(order_virtually_pay_amount) as order_virtually_pay_amount'),
            Db::raw('SUM(order_return_pay_amount) as order_return_pay_amount'),
        ];

        $selectArr = array_merge($selectArr,$countArr);
//        var_dump($selectArr);exit();
        //获取所拥有的
        $query = SystemOrderDay::query()->select($selectArr);
        $countQuery = SystemOrderDay::query()->select($countArr);
        if($data_spread_id != ''){
            $query->where(['data_spread_id' => $data_spread_id]);
            $countQuery->where(['data_spread_id' => $data_spread_id]);
        }
        if(!empty($spread_name)){
            $selectIds =  DataSpread::query()->Where([['name', 'like', '%'.$spread_name.'%']])->pluck('id');
            if(!empty($selectIds)){
                $query->whereIn('data_spread_id',$selectIds);
                $countQuery->whereIn('data_spread_id',$selectIds);
            }
        }
        if($playlet_id != '' && $playlet_id != 1){
            $query->where('system_order_day.playlet_id',$playlet_id);
            $countQuery->where('system_order_day.playlet_id',$playlet_id);
        }

        if($applet_id != '' && $applet_ids != 1){
            $query->where('system_order_day.applet_id',$applet_ids);
            $countQuery->where('system_order_day.applet_id',$applet_ids);
        }

        if(!empty($subSelect)){
            $query->whereRaw('data_spread_id in ('.$subSelect.')');
            $countQuery->whereRaw('data_spread_id in ('.$subSelect.')');
        }

        if(!empty($spreadIds)){
            $query->whereIn('data_spread_id',$spreadIds);
            $countQuery->whereIn('data_spread_id',$spreadIds);
        }
        if(!empty($date)){
            $date[0] = date('Y-m-d',$date[0]/1000);
            $date[1] = date('Y-m-d',$date[1]/1000);
            $query->whereBetween('date',$date);
            $countQuery->whereBetween('date',$date);
        }
        $query->groupBy($groupBy);

        $query->where('data_spread_id','!=',0);
        $countQuery->where('data_spread_id','!=',0);
        $countResult = $countQuery->get()->toArray();
        $countInsertData = array();
        foreach ($countResult as $key => $item){
            $countInsertData = $item;
            $countInsertData['date'] = '汇总';
            $countInsertData['data_spread_id'] = '汇总';
            $countInsertData['spread_name'] = '汇总';
            $countInsertData['playlet_name'] = '汇总';
            $countInsertData['first_user_pay_amonut']  = sprintf("%.2f",floatval($item['first_user_pay_amonut']/100));
            $countInsertData['today_after_user_pay_amonut']  = sprintf("%.2f",floatval($item['today_after_user_pay_amonut']/100));
            $countInsertData['today_first_user_pay_amonut']  = sprintf("%.2f",floatval($item['today_first_user_pay_amonut']/100));
            $countInsertData['order_wx_pay_amonut']  = sprintf("%.2f",floatval($item['order_wx_pay_amonut']/100));
            $countInsertData['order_virtually_pay_amount']  =sprintf("%.2f",floatval($item['order_virtually_pay_amount']/100));
            $countInsertData['order_amount']  = sprintf("%.2f",floatval($item['order_amount']/100));
            $countInsertData['order_return_pay_amount']  = sprintf("%.2f",floatval($item['order_return_pay_amount']/100));

            $countInsertData['today_all_user_pay_amonut'] = sprintf("%.2f",floatval($countInsertData['today_first_user_pay_amonut']+$countInsertData['today_after_user_pay_amonut']));
            if(!empty($item['today_first_user_pay_count']) && !empty($countInsertData['today_all_user_pay_amonut'])){
                $countInsertData['today_user_arpu'] = sprintf("%.2f",($countInsertData['today_all_user_pay_amonut']/$item['today_first_user_pay_count']));
            }else{
                $countInsertData['today_user_arpu'] = 0;
            }
        }
        $countData[0] = $countInsertData;

        $query->leftJoin('data_spread','system_order_day.data_spread_id','=','data_spread.id');

        if($playlet_id != '' && $playlet_id != 1){
            $query->leftJoin('playlet','system_order_day.playlet_id','=','playlet.id');
        }
        $models = $query->orderBy('date','desc')->paginate($pageSize,['*'],'page',$page);
        $items = $models->items();
        $selectData = [];
//        var_dump($items);exit();
        foreach ($items as $item){
            $data = $item->toArray();

            if($data['order_count'] == 0){
                continue;
            }
            $data['today_after_user_pay_amonut']  = sprintf("%.2f",floatval($data['today_after_user_pay_amonut']/100));
            $data['today_first_user_pay_amonut']  = sprintf("%.2f",floatval($data['today_first_user_pay_amonut']/100));
            $data['first_user_pay_amonut']  = sprintf("%.2f",floatval($data['first_user_pay_amonut']/100));
            $data['order_wx_pay_amonut']  = sprintf("%.2f",floatval($data['order_wx_pay_amonut']/100));
            $data['order_virtually_pay_amount']  =sprintf("%.2f",floatval($data['order_virtually_pay_amount']/100));
            $data['order_amount']  = sprintf("%.2f",floatval($data['order_amount']/100));
            $data['order_return_pay_amount']  = sprintf("%.2f",floatval($data['order_return_pay_amount']/100));

            $data['today_all_user_pay_amonut'] = sprintf("%.2f",floatval($data['today_first_user_pay_amonut']+$data['today_after_user_pay_amonut']));
            if(!empty($data['today_first_user_pay_count']) && !empty($data['today_all_user_pay_amonut'])){
                $data['today_user_arpu'] = sprintf("%.2f",($data['today_all_user_pay_amonut']/$data['today_first_user_pay_count']));
            }else{
                $data['today_user_arpu'] = 0;
            }

            $selectData[] =$data;
        }
        $data = $models->toArray();
        $data['data'] = array_merge($countData,$selectData);
        return $data;
    }

    public function orderSearch(Array $params,$export=0){

        $pageSize       = $params['pageSize'] ?? 10;
        $page           = $params['page'] ?? 1;
        $applet_ids     = $params['applet_ids'] ?? '';
        $playlet_id     = $params['playlet_id'] ?? '';
        $delivery_user_id  = $params['delivery_user_id'] ?? '';
        $date     = $params['date'] ?? '';
        if(empty($applet_ids)){
            return [];
        }
        $subSelect = '';

        //2023-12-11 新增可看到投放组员的数据
        if(!empty($delivery_user_id)){
//            $spreadIds = DataSpread::query()->whereIn('user_id',$delivery_user_id)->pluck('id');
            $delivery_str = implode(',',$delivery_user_id);
            $subSelect = "select `id` from `data_spread` where `user_id` in (".$delivery_str.") and `data_spread`.`deleted_at` is null";
        }else{
            //根据用户获取ID
            $userInfo = $this->getUserAppletInfo(2);
            //管理员能看到所有
            if(empty($userInfo['role']['is_admin']) && empty($userInfo['role']['is_statistical'])){
//                $spreadIds = DataSpread::query()->where(['user_id' => $userInfo['id']])->pluck('id');
                $subSelect = "select `id` from `data_spread` where `user_id` = ".$userInfo['id']." and `data_spread`.`deleted_at` is null";
            }
        }



        $selectUserArr = ['date'];
        $selectArr = ['date'];
        $groupBy = ['date'];
        $userGroupBy = ['date'];
        if($playlet_id != '' && $playlet_id != 1){
            $selectArr[] ='playlet_id';
            $groupBy[] = 'playlet_id';
        }
        if($applet_ids == '1'){
            //获取所有的小程序所绑定的短剧
            $applet_id =  $this->userAppletIds;
        }else{
            $applet_id =  $applet_ids;
        }


        $commontArr = [
            Db::raw('SUM(order_count) as order_count'),
//            Db::raw('SUM(order_wait_pay_count) as order_wait_pay_count'),
            Db::raw('SUM(order_count) as order_pay_count'),
//            Db::raw('SUM(order_cannel_count) as order_cannel_count'),
//            Db::raw('SUM(order_return_count) as order_return_count'),
            Db::raw('SUM(order_wx_pay_count) as order_wx_pay_count'),
            Db::raw('SUM(order_virtually_pay_count) as order_virtually_pay_count'),
            Db::raw('SUM(first_user_count) as first_user_count'),
            Db::raw('SUM(first_user_pay_amonut) as first_user_pay_amonut'),
            Db::raw('SUM(today_first_user_pay_amonut) as today_first_user_pay_amonut'),
            Db::raw('SUM(today_first_user_pay_count) as today_first_user_pay_count'),
            Db::raw('SUM(today_after_user_pay_amonut) as today_after_user_pay_amonut'),
            Db::raw('SUM(today_after_user_pay_count) as today_after_user_pay_count'),
            Db::raw('SUM(order_amount) as order_amount'),
            Db::raw('SUM(order_wx_pay_amonut) as order_wx_pay_amonut'),
            Db::raw('SUM(order_virtually_pay_amount) as order_virtually_pay_amount'),
            Db::raw('SUM(order_return_pay_amount) as order_return_pay_amount'),
        ];
        $selectArr = array_merge($selectArr,$commontArr);
        //获取所拥有的订单
        $query = SystemOrderDay::query()->select($selectArr);

        $countQuery = SystemOrderDay::query()->select($commontArr);

        if($playlet_id != '' && $playlet_id != 1){
            $query->where('playlet_id',$playlet_id);
            $countQuery->where('playlet_id',$playlet_id);
        }
        if(!empty($subSelect)){
            $query->whereRaw('data_spread_id in ('.$subSelect.')');
            $countQuery->whereRaw('data_spread_id in ('.$subSelect.')');
        }

        if(!empty($spreadIds)){
            $query->whereIn('data_spread_id',$spreadIds);
            $countQuery->whereIn('data_spread_id',$spreadIds);
        }
        if($applet_id != '' && $applet_ids != 1){
            $query->where('applet_id',$applet_ids);
            $countQuery->where('applet_id',$applet_ids);
        }

        if(!empty($date)){
            $date[0] = date('Y-m-d',$date[0]/1000);
            $date[1] = date('Y-m-d',$date[1]/1000);
            $query->whereBetween('date',$date);
            $countQuery->whereBetween('date',$date);
        }
        $query->groupBy($groupBy);

        $models = $query->orderBy('date','desc')->paginate($pageSize,['*'],'page',$page);
        $countResult = $countQuery->get()->toArray();
        $countInsertData = array();
        foreach ($countResult as $key => $item){
            $countInsertData = $item;
            $countInsertData['date'] = '汇总';
            $countInsertData['playlet_name'] = '汇总';
            $countInsertData['first_user_pay_amonut']  = sprintf("%.2f",floatval($item['first_user_pay_amonut']/100));
            $countInsertData['today_first_user_pay_amonut']  = sprintf("%.2f",floatval($item['today_first_user_pay_amonut']/100));
            $countInsertData['today_after_user_pay_amonut']  = sprintf("%.2f",floatval($item['today_after_user_pay_amonut']/100));
            $countInsertData['order_wx_pay_amonut']  = sprintf("%.2f",floatval($item['order_wx_pay_amonut']/100));
            $countInsertData['order_virtually_pay_amount']  =sprintf("%.2f",floatval($item['order_virtually_pay_amount']/100));
            $countInsertData['order_amount']  = sprintf("%.2f",floatval($item['order_amount']/100));
            $countInsertData['order_return_pay_amount']  = sprintf("%.2f",floatval($item['order_return_pay_amount']/100));

            $countInsertData['today_all_user_pay_amonut'] = sprintf("%.2f",floatval($countInsertData['today_first_user_pay_amonut']+$countInsertData['today_after_user_pay_amonut']));
            if(!empty($item['today_first_user_pay_count']) && !empty($countInsertData['today_all_user_pay_amonut'])){
                $countInsertData['today_user_arpu'] = sprintf("%.2f",($countInsertData['today_all_user_pay_amonut']/$item['today_first_user_pay_count']));
            }else{
                $countInsertData['today_user_arpu'] = 0;
            }
        }
        $countData[0] = $countInsertData;
        $items = $models->items();

        $userKeyVal = array();
        //用户的key val 组合
//        foreach ($userItems as $userItem){
//            $userKeyVal[$userItem['date']] =  $userItem->toArray();
//        }
        $selectData = [];
//        $countData = [];
        foreach ($items as $item){
            $data = $item->toArray();
            $data['playlet_name']  = '';
            if($playlet_id != '' && $playlet_id != 1) {
                if(!empty($item->playlet)) {
                    $data['playlet_name'] = $item->playlet->name;
                }
            }
            $data['first_user_pay_amonut']  = sprintf("%.2f",floatval($data['first_user_pay_amonut']/100));
            $data['today_first_user_pay_amonut']  = sprintf("%.2f",floatval($data['today_first_user_pay_amonut']/100));
            $data['today_after_user_pay_amonut']  = sprintf("%.2f",floatval($data['today_after_user_pay_amonut']/100));
            $data['order_wx_pay_amonut']  = sprintf("%.2f",floatval($data['order_wx_pay_amonut']/100));
            $data['order_virtually_pay_amount']  =sprintf("%.2f",floatval($data['order_virtually_pay_amount']/100));
            $data['order_amount']  = sprintf("%.2f",floatval($data['order_amount']/100));
            $data['order_return_pay_amount']  = sprintf("%.2f",floatval($data['order_return_pay_amount']/100));

            $data['today_all_user_pay_amonut'] = sprintf("%.2f",floatval($data['today_first_user_pay_amonut']+$data['today_after_user_pay_amonut']));
            if(!empty($data['today_first_user_pay_count']) && !empty($data['today_all_user_pay_amonut'])){
                $data['today_user_arpu'] = sprintf("%.2f",($data['today_all_user_pay_amonut']/$data['today_first_user_pay_count']));
            }else{
                $data['today_user_arpu'] = 0;
            }

            //判断日期有没有对应的数据
            $selectData[] =$data;
        }
        $data = $models->toArray();
        $data['data'] = array_merge($countData,$selectData);
        return $data;
    }

    public function userSearch(Array $params,$export=0){

        $pageSize       = $params['pageSize'] ?? 10;
        $pageSize = intval($pageSize);
        $page           = $params['page'] ?? 1;
        $page = intval($page);
        $applet_ids     = $params['applet_ids'] ?? '';
        $created_at     = $params['created_at'] ?? '';
        $spread_id      = $params['spread_id'] ?? ''; //推广链接id
        $user_id       = $params['user_id'] ?? ''; //推广链接id
        $date_type     = $params['date_type'] ?? '';
        $delivery_user_id  = $params['delivery_user_id'] ?? '';
        if(empty($applet_ids)){
            return [];
        }
        $subSelect = '';
        //2023-12-11 新增可看到投放组员的数据
        if(!empty($delivery_user_id)){
//            $spreadIds = DataSpread::query()->whereIn('user_id',$delivery_user_id)->pluck('id');
            $delivery_str = implode(',',$delivery_user_id);
            $subSelect = "select `id` from `data_spread` where `user_id` in (".$delivery_str.") and `data_spread`.`deleted_at` is null";
        }else{
            $userInfo = $this->getUserAppletInfo(2);
            //管理员能看到所有
            if($userInfo['role']['is_admin'] != 1){
                if(empty($userInfo['role']['is_check_user_order'])){
//                    $spreadIds = DataSpread::query()->where(['user_id' => $userInfo['id']])->pluck('id');
                    $subSelect = "select `id` from `data_spread` where `user_id` = ".$userInfo['id']." and `data_spread`.`deleted_at` is null";
                }
            }
        }

        //找所有小程序
        $appletInfo = Applet::query()->where('id',$applet_ids)->select(['id','name'])->first();

        if(!empty($appletInfo)){


            $query = Db::table('data_user_'.$appletInfo->id.' as user')
                ->select(['user.is_vip','user.give_coin','user.ml_coin','user.username','user.headimg','user.create_at','user.applet_id','user.dyeing_time'
                    ,'user.ip','user.id','user.spread_id',Db::raw('\''.$appletInfo->name.'\' as applet_name'),'data_spread.name as spread_name']);
            if(!empty($spreadIds)){
                $query->whereIn('user.spread_id',$spreadIds);
            }
            if (!empty($spread_id)) {
                $query->Where(['user.spread_id' => $spread_id]);
            }
            if(!empty($subSelect)){
                $query->whereRaw('user.spread_id in ('.$subSelect.')');
            }

            if(!empty($user_id)){
                $query->where('user.id',$user_id);
            }
            if(!empty($created_at)){
                    $created_at[0] = date('Y-m-d H:i:s',$created_at[0]/1000);
                    $created_at[1] = date('Y-m-d H:i:s',$created_at[1]/1000);
                if($date_type == 1){
                    $query->whereBetween('user.create_at',$created_at);
                }else if($date_type == 2){
                    $query->whereBetween('user.dyeing_time',$created_at);
                }
            }

            $models = $query
                ->leftJoin('data_spread','user.spread_id','=','data_spread.id')
                ->orderBy('user.id','desc')->paginate($pageSize,['*'],'page',$page);
            $items = $models->items();
            $userIds = array();
            foreach ($items as $item) {
                $userIds[] = $item->id;
            }
            $paymentkeyVal = [];
            if(!empty($userIds)){

                $paymentData = Payment::query()->select([Db::raw('SUM(amount) as order_amount'),Db::raw('count(id) as count'),'user_id'])
                    ->where(['applet_id' => $appletInfo->id])->whereIn('user_id',$userIds)
                    ->where('status',2)->groupBy(['user_id'])->get()->toArray();
                foreach ($paymentData as $paymentDatum){
                    $paymentkeyVal[$paymentDatum['user_id']] = $paymentDatum;
                }
            }
            $selectData = [];
            foreach ($items as $item){
                $data = $item;
                $data->count  = 0;
                $data->amount  = 0;
                //推广ID
                //统计充值了多少钱
                if(!empty($paymentkeyVal[$item->id])){
                    $paymentcount = $paymentkeyVal[$item->id]['count'];
                    $paymentAmount = $paymentkeyVal[$item->id]['order_amount'];
                    $data->count  = $paymentcount;
                    $data->amount  = sprintf("%.2f",$paymentAmount/100);
                }
                $selectData[] =$data;
            }
            $data = $models->toArray();
            $data['data'] = $selectData;

        }

        return $data;
    }
    public function getplayletInfo(Array $params){

        $applet_ids     = $params['applet_ids'] ?? '';

        $date     = $params['date'] ?? '';
        if(empty($applet_ids)){
            return [];
        }
        $userInfo = $this->getUserAppletInfo(2);
        //管理员能看到所有
        if($userInfo['role']['is_admin'] != 1){
            //获取这个用户的company 查找对应的小城，找到对应的短剧
            if($applet_ids == 1){
                $applet_ids = AppletCompany::query()->where(['company_id' => $userInfo['company_id']])->pluck('applet_id');
                if(empty($applet_ids)){
                    return [];
                }
                $playlet_ids = AppletPlayletRel::query()->whereIn('applet_id',$applet_ids)->pluck('playlet_id');
                if(empty($playlet_ids)){
                    return [];
                }

            }else{

                $playlet_ids = AppletPlayletRel::query()->whereIn('applet_id',[$applet_ids])->pluck('playlet_id');
                if(empty($playlet_ids)){
                    return [];
                }
            }

            $playletInfo =  Playlet::query()->whereIn('id',$playlet_ids)->select(['id as value',db::Raw('IFNULL(`alias_name`,`name`) as label')])->get();
            if(!empty($playletInfo)){
                $returnData[] = ['value' => 1,'label' => '全部短剧'];
                if($userInfo['company_id'] == 1){
                    $returnData[] = ['value' => 0,'label' => '自然流'];
                }
                $playletInfo = array_merge($returnData,$playletInfo->toArray());
                return $playletInfo;
            }
        }else{
            $playletInfo =  Playlet::query()->select(['id as value',db::Raw('IFNULL(`alias_name`,`name`) as label')])->get();
            if(!empty($playletInfo)){
                $returnData[] = ['value' => 1,'label' => '全部短剧'];
                $returnData[] = ['value' => 0,'label' => '自然流'];
                $playletInfo = array_merge($returnData,$playletInfo->toArray());
                return $playletInfo;
            }
        }
    }

    public function getUserBuy(Array $params){
        $user_id = $params['user_id'];
        $applet_id = $params['applet_id'];

        $playletdata = DataUserPayPlayletLog::query()->select(['data_user_pay_playlet_log.amount','data_user_pay_playlet_log.playlet_id as playlet_id','data_user_pay_playlet_log.playlet_number','playlet.name as playlet_name','create_at'])
            ->leftJoin('playlet','data_user_pay_playlet_log.playlet_id','=','playlet.id')
            ->where(['user_id' => $user_id,'applet_id' => $applet_id])->orderBy('create_at','desc')->get()->toArray();
        $returnData = array();
        if(!empty($playletdata)){


            foreach ($playletdata as $playletdatum){

                $playletdatum['amount'] =  $playletdatum['amount']/100;
                $playletdatum['playlet_number_name'] = '第'.$playletdatum['playlet_number'].'集';

//                $number = DataUserPayPlayletLog::query()
//                    ->where(['user_id' => $user_id,'applet_id' => $applet_id,'playlet_id' => $playletdatum->playlet_id])
//                    ->select(['playlet_number','amount','order_id','create_at'])->orderby('create_at','desc')->get()
//                    ->toArray();
//                if(!empty($number)){
//                    $reutrnNumber = array();
//                    foreach ($number as $value){
//
//                        $value['amount'] =  $value['amount']/100;
//                        $value['playlet_number_name'] = '第'.$value['playlet_number'].'集';
//                        $reutrnNumber[] = $value;
//                    }
//
//
//                    $returnData[] = [
//                        'playlet_name' => $playletdatum->playlet_name,
//                        'playlet_num' => $reutrnNumber
//                    ];
//                }
            }
        }
        return $playletdata;
    }

    public function getUserRecharge(Array $params){
        $user_id = $params['user_id'];
        $applet_id = $params['applet_id'];

        $returnData = DataUserRechargeLog::query()->select(['create_at','amount','is_vip','ml_coin','give_coin'])
            ->where(['user_id' => $user_id,'applet_id' => $applet_id])->orderBy('create_at','desc')->get();

        foreach ($returnData as $returnDatum){
            $returnDatum->amount =  $returnDatum->amount/100;
        }
        return $returnData;
    }

    public function getUserView(Array $params){

        $pageSize       = $params['pageSize'] ?? 20;
        $pageSize = intval($pageSize);
        $page           = $params['page'] ?? 1;
        $page = intval($page);
        $user_id = $params['user_id'];
        $playlet_id = $params['playlet_id'] ?? 0;
        $applet_id = $params['applet_id'];
        $view_at     = $params['view_at'];

        $start_time = $view_at[0]/1000;
        $end_time = $view_at[1]/1000;
        $view_at[0] = date('Y-m-d H:i:s',$start_time);
        $view_at[1] = date('Y-m-d H:i:s',$end_time);

        $startDay =  strtotime(date('Y-m-01',$start_time));
        $endDay =  strtotime(date('Y-m-01',$end_time));
        // 计算两个时间戳之间相隔的天数
        $daysDiff = ($endDay - $startDay) / (60 * 60 * 24);

        if($daysDiff > 60){
            return $this->response(SystemCode::SYSTEM_ERROR, '查询的时间区间，跨度只能在2个月内');
        }
//        //查询日期需要大于2024-01-01
        if($start_time < 1704038400){
            return $this->response(SystemCode::SYSTEM_ERROR, '查询日期需大于2024年');
        }
        $currentDate = date('Y-m'); // 获取当前月份
        $nextMonthDate = strtotime("+1 month", strtotime($currentDate)); // 获取下个月的日期并转换成时间戳
        if ($end_time > $nextMonthDate) {
            return $this->response(SystemCode::SYSTEM_ERROR, '结束时间不能大于本月');
        }
        $startMonth =  date('Ym',$start_time);
        $endMonth =  date('Ym',$end_time);
        $query = Db::table('data_user_viewing_log_'.$startMonth)
            ->select(['playlet_id','view_at','playlet_number','playlet.name as playlet_name'])
            ->leftJoin('playlet','playlet_id','=','playlet.id')
            ->where(['user_id' => $user_id,'applet_id' => $applet_id])
            ->whereBetween('view_at',$view_at);
        if(!empty($playlet_id)){
            $query->where('playlet_id',$playlet_id);
        }
        if($startMonth != $endMonth){
            $unionSelect = Db::table('data_user_viewing_log_'.$endMonth)
                    ->select(['playlet_id','view_at','playlet_number','playlet.name as playlet_name'])
                    ->leftJoin('playlet','playlet_id','=','playlet.id')
                    ->where(['user_id' => $user_id,'applet_id' => $applet_id])
                    ->whereBetween('view_at',$view_at);
            if(!empty($playlet_id)){
                $unionSelect->where('playlet_id',$playlet_id);
            }
            $query->union($unionSelect);
        }
        $models = $query->orderBy('view_at','desc')->paginate($pageSize,['*'],'page',$page);

        return $this->response(SystemCode::SYSTEM_SUCCESS, '查询成功',$models);
    }


    public function getSearchSpread($params){

        $applet_id     = $params['applet_id'] ?? '';
        $delivery_user_id  = $params['delivery_user_id'] ?? '';
        if(empty($applet_id)){
            return [];
        }
        $query = DataSpread::query()->select(['id as value','name as label']);
        //2023-12-11 新增可看到投放组员的数据
        if(!empty($delivery_user_id)){
            $query->whereIn('user_id',$delivery_user_id);
        }else{
            $userInfo = $this->getUserAppletInfo(2);
            //管理员能看到所有
            if($userInfo['role']['is_admin'] != 1){
                if(empty($userInfo['role']['is_check_user_order'])){
                    $query->where('user_id',$userInfo['id']);
                }
            }
        }
        $query->where('applet_id',$applet_id)->orderBy('id','desc');
        return  $query->get();
    }
}